package com.picturehistory.core.jersey.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.jdo.support.JdoDaoSupport;
import org.springframework.transaction.annotation.Transactional;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.picturehistory.core.jersey.model.User;

public class UserDAOJDOImpl extends JdoDaoSupport implements UserDAO {
	private final Logger logger = LoggerFactory.getLogger(UserDAOJDOImpl.class);
	
	@Transactional
	public User getUserByIdNumber(String idNumber) {
		Map<String, String> values = new HashMap<String, String>();
		values.put("myIdNumber", idNumber);
		
		List<User> ret;
		
		try {
			ret = (List<User>) getJdoTemplate().find(User.class, "idNumber==myIdNumber", "String myIdNumber", values);
		} catch(Exception e) {
			ret = null;
		}
		
		if (ret == null || ret.size() == 0) {
			logger.info("there is no matching User data for idNumber: " + idNumber);
			return null;
		} else {
			//there must be one and only one instance
			logger.info("found User data for idNumber: " + idNumber);
			logger.info("retreiving: " + ret.toString());
			return ((List<User>) getJdoTemplate().detachCopyAll(ret)).get(0); 
		}
	}
	
	public User getUserByUserId(String userId) { //if encryption required do NOT user this
		Key key = KeyFactory.createKey(User.class.getSimpleName(), "user:"+userId);
		User ret;
		
		try {
			ret = (User) getJdoTemplate().getObjectById(User.class, key);
			logger.info("retreiving: " + ret.toString());
		} catch(Exception e) {
			ret = null;
		}
		
		return ret;
	}
	
	@Transactional
	public User getDetachedUserByUserId(String userId) {
		Key key = KeyFactory.createKey(User.class.getSimpleName(), "user:"+userId);
		User ret;
		
		try {
			ret = (User) getJdoTemplate().getObjectById(User.class, key);
			logger.info("retreiving: " + ret.toString());
		} catch(Exception e) {
			ret = null;
		}
		
		return (User) getJdoTemplate().detachCopy(ret);
	}

	public void storeUser(User u) throws DataAccessException {
		logger.info("storing: " + u.toString());
		getJdoTemplate().makePersistent(u);
		logger.info("User data successfully stored");
	}
}
